package com.ls.bpmn.controller;

import com.ls.bpmn.dto.NodeDTO;
import com.ls.common.Constast;
import com.ls.common.ResultObj;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.model.bpmn.BpmnModelInstance;
import org.camunda.bpm.model.bpmn.instance.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author lisheng
 * @Date 2025/05/08 14:05
 **/
@RestController
@RequestMapping("/node")
public class NodeController {

    @Autowired
    private RepositoryService repositoryService;

    @GetMapping("/process-definition/{id}")
    public ResultObj getNodeList(@PathVariable String id){
      try {
          List<NodeDTO> list = this.getNodeByProcessDefinitionId(id);
          return new ResultObj(Constast.OK, "操作成功", list);
      }catch (Exception e){
          return new ResultObj(Constast.ERROR,"操作失败!",e.getMessage());
      }
    }

    public List<NodeDTO> getNodeByProcessDefinitionId(String processDefinitionId) throws Exception{
        try{
            BpmnModelInstance modelInstance = repositoryService.getBpmnModelInstance(processDefinitionId);
            Collection<Task> list = modelInstance.getModelElementsByType(Task.class);
            List<NodeDTO> nodes = new ArrayList<>();
            for (Task t : list) {
                nodes.add(new NodeDTO(t.getId(),t.getName()));
            }
            return nodes;
        }catch (Exception e){
            throw new Exception(e.getMessage());
        }
    }
}
